from flask import Flask, request, jsonify, send_from_directory
import os
from urllib.parse import quote
import requests
import json
from index import crop_and_save, crop_and_save_with_summary
from amazon import amazon_crop_and_save, amazon_crop_and_save_with_summary  # 假设 index.py 和 app.py 在同一目录下
from flask_cors import CORS

app = Flask(__name__)
# 启用跨域访问
CORS(app)

# 设置上传文件的保存路径
UPLOAD_FOLDER = 'uploads'
DOWNLOAD_FOLDER = 'download'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER

def normalize_path(path):
    """统一路径分隔符为正斜杠"""
    return path.replace('\\', '/')

def download_file_from_url(url, save_path):
    """从URL下载文件并保存到指定路径"""
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 确保请求成功
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        return True
    except Exception as e:
        print(f"下载文件时出错: {str(e)}")
        return False
 
@app.route('/download/<path:filename>')
def download_file(filename):
    return send_from_directory(directory='download', path=filename)

@app.route('/upload', methods=['POST'])
def upload_file():
    try:
        if 'file' not in request.files:
            return jsonify({"message": "没有文件", "code": 0}), 200
        
        file = request.files['file']
        
        if file.filename == '':
            return jsonify({"message": "没有选择文件", "code": 0}), 200
        
        if file:
            filename = (file.filename)
            file_path = normalize_path(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            file.save(file_path)

            # 调用裁剪功能
            output_file = normalize_path(os.path.join(app.config['DOWNLOAD_FOLDER'], filename))
            crop_and_save(file_path, output_file)
            
            return jsonify({
                "message": "处理成功", 
                "filename": filename, 
                "output": "http://110.41.39.120:5000/download/" + filename, 
                "code": 1
            }), 200
    except Exception as e:
        # 捕获所有异常并返回错误信息
        return jsonify({"message": str(e), "code":0}), 200

@app.route('/upload_with_summary', methods=['POST'])
def upload_with_summary():
    try:
        # 获取JSON数据
        data = request.get_json()
        if not data:
            return jsonify({"message": "没有提供JSON数据", "code": 0}), 200

        # 获取文件URL
        file_url = data.get('file_url')
        if not file_url:
            return jsonify({"message": "没有提供文件URL", "code": 0}), 200
        
        # 从JSON数据中获取参数
        shipping_id = data.get('shipping_id', '')
        shipments = data.get('shipments', [])
        
        # 检查shipments数量是否超过12个
        if len(shipments) > 40:
            return jsonify({
                "message": "超出订单限制，请手动处理。", 
                "code": 0
            }), 200
            
        # 从URL中提取文件名
        filename = os.path.basename(file_url.split('?')[0])  # 移除URL参数
        if not filename.lower().endswith('.pdf'):
            filename += '.pdf'
            
        # 下载文件
        file_path = normalize_path(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        if not download_file_from_url(file_url, file_path):
            return jsonify({"message": "下载文件失败", "code": 0}), 200
        
        # 从JSON数据中获取参数
        total_boxes = data.get('total_boxes', 1)
        warehouse = data.get('warehouse', '')
        date = data.get('date')

        # 调用裁剪功能并添加总结页
        output_file = normalize_path(os.path.join(app.config['DOWNLOAD_FOLDER'], filename))
    
        crop_and_save_with_summary(
            file_path, 
            output_file,
            shipping_id,
            shipments,
            total_boxes,
            warehouse,
            date
        )
        
        return jsonify({
            "message": "处理成功", 
            "filename": filename, 
            "output": "http://110.41.39.120:5000/download/" + filename, 
            "code": 1
        }), 200
    except Exception as e:
        # 捕获所有异常并返回错误信息
        return jsonify({"message": str(e), "code":0}), 200

@app.route('/amzon_upload_with_summary', methods=['POST'])
def amzon_upload_with_summary():
    try:
        # 获取JSON数据
        data = request.get_json()
        if not data:
            return jsonify({"message": "没有提供JSON数据", "code": 0}), 200

        # 获取文件URL
        file_url = data.get('file_url')
        if not file_url:
            return jsonify({"message": "没有提供文件URL", "code": 0}), 200
        
        # 从JSON数据中获取参数
        shipping_id = data.get('shipping_id', '')
        shipments = data.get('shipments', [])
        
        # 检查shipments数量是否超过12个
        if len(shipments) > 40:
            return jsonify({
                "message": "超出订单限制，请手动处理。", 
                "code": 0
            }), 200
            
        # 从URL中提取文件名
        filename = os.path.basename(file_url.split('?')[0])  # 移除URL参数
        if not filename.lower().endswith('.pdf'):
            filename += '.pdf'
            
        # 下载文件
        file_path = normalize_path(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        if not download_file_from_url(file_url, file_path):
            return jsonify({"message": "下载文件失败", "code": 0}), 200
        
        # 从JSON数据中获取参数
        total_boxes = data.get('total_boxes', 1)
        warehouse = data.get('warehouse', '')
        date = data.get('date')

        # 调用裁剪功能并添加总结页
        output_file = normalize_path(os.path.join(app.config['DOWNLOAD_FOLDER'], filename))

        amazon_crop_and_save_with_summary(
            file_path, 
            output_file,
            shipping_id,
            shipments,
            total_boxes,
            warehouse,
            date
        )
        
        return jsonify({
            "message": "处理成功", 
            "filename": filename, 
            "output": "http://110.41.39.120:5000/download/" + filename, 
            "code": 1
        }), 200
    except Exception as e:
        # 捕获所有异常并返回错误信息
        return jsonify({"message": str(e), "code":0}), 200

if __name__ == '__main__':
    # 设置主机为0.0.0.0，允许局域网访问
    # 设置端口为5000（可以根据需要修改）
    # 在生产环境中建议关闭debug模式
    app.run(host='0.0.0.0', port=5000, debug=False)